package app

import (
	"gitee.com/CrazyMage/lite-note/internal/entity"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"os"
	"time"
)

const (
	_defaultAttempts = 20
	_defaultTimeout  = time.Second
)

func init() {

	databaseURL, ok := os.LookupEnv("MYSQL_URL")

	if !ok || len(databaseURL) == 0 {
		log.Fatalf("migrate: environment variable not declared: MYSQL_URL")
	}

	//databaseURL += "?sslmode=disable"

	var (
		attempts = _defaultAttempts
		err      error
		db       *gorm.DB
	)

	// 重试连接数据库
	for attempts > 0 {
		db, err = gorm.Open(mysql.Open(databaseURL), &gorm.Config{})
		if err == nil {
			break
		}
		attempts--
		log.Printf("Migrate: mysql is trying to connect, attempts left: %d", attempts)
		time.Sleep(_defaultTimeout)
	}
	if err != nil {
		log.Fatalf("Migrate: mysql connect error: %s", err)
	}

	// 获取底层 SQL 连接用于关闭
	sqlDB, _ := db.DB()
	defer sqlDB.Close()

	// GORM 自动迁移核心逻辑
	err = db.AutoMigrate(
		&entity.User{}, // 用户表
		&entity.Note{}, // 任务表
		// 在此添加其他模型...
	)

	if err != nil {
		log.Fatalf("Migrate: failed to auto-migrate: %v", err)
	}

	log.Printf("Migrate: up success")
}
